﻿<%@ WebHandler Language="C#" Class="TaskDispenseInfo" %>

using System;
using System.Web;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using System.Collections.Generic;
using Chenxin.Lib.Utility;
using System.Web.Script.Serialization;
using System.Collections;

public class TaskDispenseInfo : AjaxHandlerBase
{
    public string jsonData = string.Empty;
    public string strType = string.Empty;
    public string strRecordId = string.Empty;
    public string strOperate = string.Empty;
    
    //构造函数
    public TaskDispenseInfo()
    {
        //添加分配任务
        htTypePermit.Add("add", Constants.Permit_TaskDispenseAdd);
        //删除分配任务
        htTypePermit.Add("del", Constants.Permit_TaskDispenseDel);
        //分配任务详情
        htTypePermit.Add("detail", Constants.Permit_DetailTask);
    }
    
    override public void RequestProcess(HttpContext context)  
    {
        context.Response.ContentType = "text/plain";
        context.Response.Buffer = true;
        context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";

        if (!string.IsNullOrEmpty(context.Request.Params["type"]))
        {
            strType = Convert.ToString(context.Request.Params["type"]);
        }
        if (!string.IsNullOrEmpty(context.Request.Params["RecordId"]))
        {
            strRecordId = Convert.ToString(context.Request.Params["RecordId"]);
        }
        if (!string.IsNullOrEmpty(context.Request.Params["op"]))
        {
            strOperate = Convert.ToString(context.Request.Params["op"]);

            switch (strOperate.Trim())
            {
                case "search":
                    SearchTaskTable(context);
                    break;
                case "detail":
                    ShowTasksDetail(context);
                    break;
                case "update":
                    UpdateTask(context);
                    break;
                case "del":
                    DeleteTaskTable(context);
                    break;
                case "add":
                    AddTaskTable(context);
                    break;
                case "gethousetasklist":
                    getHouseTaskList(context);
                    break;
                default:
                    break;
            }
 
        }

        
    }

    /// <summary>
    /// 显示任务列表(得到一个Task的Table)
    /// </summary>
    /// <param name="context"></param>
    public void InitTaskTable(HttpContext context, string strWhere)
    {
        try
        {
            int count = 0;
            Constants.Pagination stuPg = new Constants.Pagination();
            
            //页码
            int strPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            //页显示行数
            int strPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数
            //排序
            string strOrderField = "Addtime desc";
            //strType来判断返回不同的查询条件
            switch (strType.Trim())
            {
                case "AllTask":
                    strWhere += "and AddPersonId = '" + CurrentUserInfo.UserId + "'";
                    break;
                case "MyTask":
                    strWhere += "and taskReceiverId = '" + CurrentUserInfo.UserId + "'";
                    break;
                default:
                    break;
            }

            //欲选择字段列表 
            string FieldList = "RecordId,Title,relatedCaption,AddPerson,TaskType,TaskBeginDay,TaskEndDay,Status ";
            //子查询欲选择字段列表
            string TableFieldList = "RecordId,Title,AddPerson,relatedCaption,TaskType,Convert(varchar(10),TaskBeginDay,120) as TaskBeginDay,Convert(varchar(10),TaskEndDay,120) as TaskEndDay, case Status when 0 then '待处理' when 1 then '已处理' end as Status";

            //所要查询的表名
            string TableName = "Tasks_BaseInfo";
            //根据sql执行查询
            DataSet ds = Chenxin.Lib.House.DAL.Tasks_BaseInfo.GetList(strPageSize, strPageIndex, strOrderField, TableName, strWhere, FieldList, TableFieldList, true);
            //数据量
            count = (int)ds.Tables[1].Rows[0][0];

            string strHtml = string.Empty;

            if (!GetHouseListHtml(ds, out strHtml))
            {
                context.Response.Write(retExecResult(Constants.ExecResult.Error, "生成HTML错误", ""));
            }
            stuPg.count = count;
            stuPg.data = strHtml.ToString();

            context.Response.Write(retExecResult(Constants.ExecResult.Succ, "OK", stuPg));   

        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        } 
    }

    private bool GetHouseListHtml(DataSet dslist, out string strHtml)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("<table width=\"100%\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\">");
        sb.Append("<thead>");
        sb.Append("<tr>");
        sb.Append("<th width=\"5%\">操作</th>");
        sb.Append("<th width=\"26%\">主题</th>");
        sb.Append("<th width=\"23%\">房源地址</th>");
        sb.Append("<th width=\"10%\">分配人</th>");
        sb.Append("<th width=\"10%\">任务类型</th>");
        sb.Append("<th width=\"10%\">开始时间</th>");
        sb.Append("<th width=\"10%\">结束时间</th>");
        sb.Append("<th width=\"6%\">状态</th>");
        sb.Append("</tr>");
        sb.Append("</thead>");
        sb.Append("<tbody>");

        foreach (DataRow row in dslist.Tables[0].Rows)
        {
            sb.AppendFormat("<tr id=\"{0}\" class=\"tr_houselist\">", row["RecordId"].ToString());

            sb.AppendFormat("<td><a name=\"{0}\" id=\"btndetail\" href=\"#\" class=\"a_detail\">详情</a>", row["RecordId"].ToString());
            
            //对过长的title进行长度截取
            if (row["Title"].ToString().Length > 15)
            {
                sb.AppendFormat("<td>{0}</td>", row["Title"].ToString().Substring(0, 15) + "...");
            }
            else
            {
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Title", ""));
            }
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "relatedCaption", ""));
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "AddPerson", ""));
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "TaskType", ""));
            sb.AppendFormat("<td>{0:yyyy-MM-dd}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "TaskBeginDay", ""));
            sb.AppendFormat("<td>{0:yyyy-MM-dd}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "TaskEndDay", ""));
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Status", ""));

            sb.Append("</tr>");
        }

        sb.Append("</tbody></table>");

        strHtml = sb.ToString();
        return true;
    }
    
    /// <summary>
    /// 通过任务ID取到此任务的详细信息
    /// </summary>
    /// <param name="context"></param>
    public void ShowTasksDetail(HttpContext context)
    {

        try
        {
            Chenxin.Lib.House.Entity.Tasks_BaseInfo lsTasksInfo = Chenxin.Lib.House.DAL.Tasks_BaseInfo.GetModel(new Guid(strRecordId));

            context.Response.Write(retExecResult(Constants.ExecResult.Succ, "OK", lsTasksInfo));
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
           
           
    }

    /// <summary>
    /// 更新任务状态
    /// </summary>
    /// <param name="context"></param>
    public void UpdateTask(HttpContext context)
    {
        try
        {

            Chenxin.Lib.House.Entity.Tasks_BaseInfo clhet = (Chenxin.Lib.House.Entity.Tasks_BaseInfo)Chenxin.Lib.Utility.JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.Tasks_BaseInfo));

            Chenxin.Lib.House.Entity.Tasks_BaseInfo clhetb = Chenxin.Lib.House.DAL.Tasks_BaseInfo.GetModel(clhet.RecordId);

            clhetb.Title = clhet.Title;
            clhetb.TaskType = clhet.TaskType;
            clhetb.TaskBeginDay = clhet.TaskBeginDay;
            clhetb.TaskEndDay = clhet.TaskEndDay;
            clhetb.Description = clhet.Description;
            clhetb.Status = clhet.Status;
            clhetb.DealDay = clhet.DealDay;
            clhetb.DealDescription = clhet.DealDescription;

            string strMsg = Chenxin.Lib.House.BLL.Tasks_BaseInfo.Update(clhetb);
            
            //添加用户操作日志
            AddLog("" + CurrentUserInfo.UserName + "更新了一个任务:" + clhetb.Title + "",
                    OperationType.OperationTypeComboList()["OprType_TaskEdit"].ToString());
            
            context.Response.Write(retExecResult(Constants.ExecResult.Succ, strMsg, ""));
        
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }    
    }

    /// <summary>
    /// 添加任务信息
    /// </summary>
    /// <param name="context"></param>
    public void AddTaskTable(HttpContext context)
    {

        try
        {
            //转换成实体
            Chenxin.Lib.House.Entity.Tasks_BaseInfo model = (Chenxin.Lib.House.Entity.Tasks_BaseInfo)
                                                                Chenxin.Lib.Utility.JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.Tasks_BaseInfo));
            model.RecordId = Guid.NewGuid();
            model.Status = 0;
            model.Addtime = DateTime.Now;
            model.AddPersonId = CurrentUserInfo.UserId;
            model.AddDepartId = CurrentUserInfo.DepartId;
            model.AddCompanyId = CurrentUserInfo.CompanyId;
            model.AddCompany = CurrentUserInfo.CompanyName;
            model.CityId = CurrentUserInfo.CityId;
            model.CityName = CurrentUserInfo.CityName;

            string strMsg = Chenxin.Lib.House.BLL.Tasks_BaseInfo.Add(model);

            //添加用户操作日志
            AddLog("" + model.AddPerson + "添加了一个任务:" + model.Title + "",
                    OperationType.OperationTypeComboList()["OprType_TaskAdd"].ToString());
            
            context.Response.Write(retExecResult(Constants.ExecResult.Succ, strMsg, ""));
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
  
    }
    
    /// <summary>
    /// 删除任务信息
    /// </summary>
    /// <param name="context"></param>
    public void DeleteTaskTable(HttpContext context)
    {
        try
        {
            strRecordId = context.Request.Params["modelid"].ToString();
            Chenxin.Lib.House.Entity.Tasks_BaseInfo clhetb = Chenxin.Lib.House.DAL.Tasks_BaseInfo.GetModel(new Guid(strRecordId));
            
            string strMsg = Chenxin.Lib.House.BLL.Tasks_BaseInfo.Delete(new Guid(strRecordId));

            //添加用户操作日志 2010-5-11 王玮 Add
            AddLog("" + CurrentUserInfo.UserName + "删除了一个任务:" + clhetb.Title + "",
                    OperationType.OperationTypeComboList()["OprType_TaskDel"].ToString());
            
            context.Response.Write(retExecResult(Constants.ExecResult.Succ, strMsg, ""));
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }  
    }

    /// <summary>
    /// 查询任务信息
    /// </summary>
    /// <param name="context"></param>
    public void SearchTaskTable(HttpContext context)
    {
       
        //查询条件
        string strWhere = "1=1";
        //接收人ID
        if (!string.IsNullOrEmpty(context.Request.Params["divSearchTaskUserId"]))
        {
            strWhere += "and taskReceiverId = '" + new Guid(context.Request.Params["divSearchTaskUserId"]) + "'";
        }
        //接收人部门ID
        else if (!string.IsNullOrEmpty(context.Request.Params["divSearchDepartmentId"]))
        {
            strWhere += "and ReceiverDepartId = '" + new Guid(context.Request.Params["divSearchDepartmentId"]) + "'";
        }
        //开始时间
        if (!string.IsNullOrEmpty(context.Request.Params["txtsearchstartime"]))
        {
            strWhere += "and convert(varchar(10),(convert(datetime,TaskBeginDay,120)),120) >= '" + context.Request.Params["txtsearchstartime"].ToString() + "'";
        }
        //结束时间
        if (!string.IsNullOrEmpty(context.Request.Params["txtsearchendtime"]))
        {
            strWhere += "and convert(varchar(10),(convert(datetime,TaskEndDay,120)),120) <= '" + context.Request.Params["txtsearchendtime"].ToString() + "'";
        }
        //状态
        if (!string.IsNullOrEmpty(context.Request.Params["divSearchTaskStatus"]))
        {
            strWhere += "and Status = '" + int.Parse(context.Request.Params["divSearchTaskStatus"]) + "'";
        }
        
        //根据查询条件生成一个任务Table
        InitTaskTable(context, strWhere);
        
    }

    //返回值説明     ：响应字符串
    //功能詳細       ：某一房屋对应任务信息
    //作成者         ：hejifeng
    //作成日         ：2010-04-27
    //修改者         ：
    //修改日         ：
    //*******************************************
    private void getHouseTaskList(HttpContext context)
    {
        string strRet;
        try
        {
            string houseid = context.Request.Params["houseid"];
            int PageIndex = 1;
            int PageSize = 10;
            
            //页码        
            if (!string.IsNullOrEmpty(context.Request.Params["pageindex"]))
            {
                PageIndex = int.Parse(context.Request.Params["pageindex"]) + 1;
            }
            //页显示行数
            if (!string.IsNullOrEmpty(context.Request.Params["pagesize"]))
            {
                PageSize = int.Parse(context.Request.Params["pagesize"]);
            }

            string OrderField = "Tasks_BaseInfo.Addtime desc";
            string StrWhere = "relatedId='" + houseid + "'";
            string FieldList = "Title,taskReceiver,ReceiverDepart,TaskType,TaskBeginDay,TaskEndDay";
            string TableFieldList = "Title,taskReceiver,ReceiverDepart,TaskType,convert(nvarchar(10),TaskBeginDay,120) as TaskBeginDay,convert(nvarchar(10),TaskEndDay,120) as TaskEndDay";
            string TableName = "Tasks_BaseInfo";

            //根据sql执行查询
            DataSet ds = null;
            if (PageIndex == 1)
            {
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
                string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_INFO_DISPEN, houseid);
                ds = cs.GetDataSet(strCachKey);

                if (!cs.Hit)
                {
                    ds = Chenxin.Lib.House.DAL.Tasks_BaseInfo.GetList(PageSize, PageIndex, OrderField, TableName, StrWhere, FieldList, TableFieldList, true);
                    if (ds != null)
                        cs.Set(strCachKey, ds, DateTime.Now.AddMinutes(5));
                }
            }
            else
            {
                ds = Chenxin.Lib.House.DAL.Tasks_BaseInfo.GetList(PageSize, PageIndex, OrderField, TableName, StrWhere, FieldList, TableFieldList, true);
            }
     
            strRet = retExecResult(Constants.ExecResult.Succ, "", retPagination(ds));
            context.Response.Write(strRet);
        }
        catch (Exception ex)
        {
            strRet = retExecResult(Constants.ExecResult.Error, ex.Message, "");
            context.Response.Write(strRet);
        }
    }

    //生成html
    private Constants.Pagination retPagination(DataSet ds)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        sb.Append("<table id=\"showFenPei\" width=\"100%\" border=\"0\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\"><thead>");
        sb.Append("<tr class=\"tab_line4\"><td width=\"30%\"><b>主题</b></td><td width=\"40%\"><b>接收人</b></td><td width=\"10%\"><b>任务类型</b></td><td width=\"10%\"><b>开始时间</b></td><td width=\"10%\"><b>结束时间</b></td></tr>");
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            sb.AppendFormat("<tr class=\"tab_line5\"><td title=\"{0}\">{0}</td><td title=\"{1}/{2}\">{1}/{2}</td><td title=\"{3}\">{3}</td><td title=\"{4}\">{4}</td><td title=\"{5}\">{5}</td></tr>", dr[0], dr[1], dr[2], dr[3], dr[4], dr[5]);
        }
        sb.Append("</thead></table>");

        Constants.Pagination stuPag = new Constants.Pagination();
        stuPag.count = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
        stuPag.data = sb.ToString();

        return stuPag;
    }
    //*******************************************
    //功能概要       ：响应字符串
    //参数説明       ：strMsg 消息 
    //返回值説明     ：void
    //功能詳細       ：权限检查
    //作成者         ：chen.yugong 
    //作成日         ：2010-05-20
    //修改者         ：
    //修改日         ：
    //*******************************************
    public override bool CustomerCheckPermint(HttpContext context, out string strMsg)
    {
        if (context.Request["op"] != null)
        {
            string op = context.Request["op"].ToLower();

            if (op.Equals("checkpermit") && "add".Equals(context.Request["code"].ToLower()))
            {
                Chenxin.Lib.House.Entity.House_BaseInfo model = null;
                try
                {
                    model = (Chenxin.Lib.House.Entity.House_BaseInfo)Chenxin.Lib.Utility.JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.House_BaseInfo));
                }
                catch (Exception e)
                {
                    strMsg = "{success:0,msg:'" + e.Message + "',data:''}";
                    return false;
                }
               
                if (CurrentUserInfo.ContainsPermit(Constants.Permit_TaskDespense_All))
                {
                    strMsg = "{success:1,msg:'',data:{permit:true}}";
                    return true;
                }

                else if (CurrentUserInfo.ContainsPermit(Constants.Permit_TaskDespense_City))
                {
                    if (CurrentUserInfo.CityId.Equals(model.CityId))
                    {
                        strMsg = "{success:1,msg:'',data:{permit:true}}";
                        return true;
                    }
                    else
                    {
                        strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
                        return false;
                    }
                }

                else if (CurrentUserInfo.ContainsPermit(Constants.Permit_TaskDespense_Company))
                {
                    if (CurrentUserInfo.CompanyId.Equals(model.CompanyId))
                    {
                        if (!checkDepartPermit(context))
                        {
                            strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
                            return false;
                        }
                        else
                        {
                            strMsg = "{success:1,msg:'',data:{permit:true}}";
                            return true;
                        }
                    }
                    else
                    {
                        strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
                        return false;
                    }
                }
                else
                {
                   if (CurrentUserInfo.DepartId.Equals(model.OprDepartId))
                    {
                        if (!checkDepartPermit(context))
                        {
                            strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
                            return false;
                        }
                        else
                        {
                            strMsg = "{success:1,msg:'',data:{permit:true}}";
                            return true;
                        }
                    }
                    else
                    {
                        strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
                        return false;
                    }
                }
            }
        }
        strMsg = "{success:1,msg:'',data:{permit:true}}";
        return true;
    }
    //*******************************************
    //功能概要       ：部门内有无封盘解盘权限
    //参数説明       ：context 上下文
    //返回值説明     ：bool
    //功能詳細       ：部门内有无封盘解盘权限
    //作成者         ：chen.yugong 
    //作成日         ：2010-05-19
    //修改者         ：
    //修改日         ：
    //*******************************************
    public bool checkDepartPermit(HttpContext context)
    {
        //检查有无权限
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.AppendFormat(" (Departid = '{0}' AND  Userid= '{1}') ", CurrentUserInfo.DepartId, CurrentUserInfo.UserId);
        DataSet ds = Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.GetList(sb.ToString());
        if (ds.Tables[0].Rows.Count < 1)
        {
            return false;
        }
        return true;
    }
}